package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.config.exceptionhandler.GuliException;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


@Service
public class OssServiceImpl implements OssService {


    @Override
    public String uploadFileAvatar(MultipartFile file) {

        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        //创建OSS实例
        try {
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

            //获取上传文件流
            InputStream inputStream = file.getInputStream();


            //获取文件名称
            String fileName = file.getOriginalFilename();
            //在文件名前添加唯一随机值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid + fileName;


            //文件按日期分类（工具类）
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            fileName = dataPath + "/" + fileName;

            //文件上传至阿里云,
            //参数2:上传到OSS文件路径和文件名称；参数3:上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);

            //关闭
            ossClient.shutdown();

            //上传之后文件路径返回，需要把上传到阿里云oss路径手动拼接出来
            String url = "http://" + bucketName + "." + endPoint + "/" + fileName;
            return url;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
